# -*- coding: utf-8 -*-
# @Time    : 2022/11/1 16:53
# @Author  : yangyuexiong
# @Email   : yang6333yyx@126.com
# @File    : __init__.py.py
# @Software: PyCharm

import os
import sys

"""
PyInstaller 5.7.0 及以上需要屏蔽所有print, 否则打包后启动.exe文件时候会报错.
如果需要开启print需要降级到 PyInstaller 5.6.2 后注释: sys.stdout = open(os.devnull, "w")
更新日志
    https://pyinstaller.org/en/stable/CHANGES.html#id2
"""
sys.stdout = open(os.devnull, "w")

from flask import Flask, request, Blueprint, jsonify
from flask.views import MethodView
from flask_cors import CORS

from commands.app_commands.WeChat.main import WeChatAuto
from commands.app_commands.Excel.excel_base.main import ExcelHandle
from commands.app_commands.Excel.excel_read.main import ExcelReadHandle
from commands.app_commands.Excel.excel_write.main import ExcelWriteHandle
from commands.app_commands.Excel.excel_delete.main import ExcelDeleteHandle
from commands.app_commands.Excel.excel_clear.main import ExcelClearHandle
from commands.app_commands.Excel.excel_insert.main import ExcelInsertHandle
from commands.app_commands.Excel.excel_sort.main import ExcelSortHandle

# wx_path = "C:/soft/other/WeChat/WeChat.exe"
wx_path = "D:/Program Files (x86)/tencent/WeChat/WeChat.exe"


def api_result(code=None, message=None, data=None, expand=None, details=None, status=None):
    result = {
        "code": code,
        "message": message,
        "data": data,
        "expand": expand
    }

    if not result['data']:
        result.pop('data')
    if not result['expand']:
        result.pop('expand')
    return jsonify(result)


api = Blueprint('api', __name__)


class WeChatSendMessageApi(MethodView):
    """微信消息发送相关Api"""

    def post(self):
        """批量发送消息"""

        wx_auto = WeChatAuto(path=wx_path)
        data = request.get_json()
        is_excel = data.get('is_excel')
        excel_path = data.get('excel_path')
        wx_auto.wx_send_message(is_excel=is_excel, excel_path=excel_path)

        # user_list1 = [
        #     {"wx_code": "YYx_33", "message": "你好呀 123"},
        #     {"wx_code": "YangYuExionGaini72", "message": "你好呀 456"}
        # ]
        # wx_auto.wx_send_message(user_list=user_list1)

        return api_result(code=200, message='操作成功')


class WeChatPyqAuthApi(MethodView):
    """微信朋友圈权限相关Api"""

    def post(self):
        """批量修改朋友圈权限"""

        wx_auto = WeChatAuto(path=wx_path)
        data = request.get_json()
        is_excel = data.get('is_excel')
        excel_path = data.get('excel_path')
        wx_auto.wx_edit_pyq_auth(is_excel=is_excel, excel_path=excel_path)

        return api_result(code=200, message='操作成功')


class DevProcess(MethodView):
    """开发流程Api"""

    def get(self):
        """获取流程"""
        return 'GET DevProcess'

    def post(self):
        """创建流程"""

        data = request.get_json()
        process_list = data.get('process_list')

        return 'POST DevProcess'


class ExcelAutoSheetApi(MethodView):
    """Excel-Sheet相关Api"""

    def post(self):
        """Sheet list"""

        data = request.get_json()
        excel_path = data.get('excel_path')

        eh = ExcelHandle(excel_path=excel_path)
        eh.excel_open()
        result = {
            "sheet_list": eh.get_sheet_list(),
            "sheet_obj_list": eh.get_sheet_obj_list()
        }
        return api_result(code=200, message='操作成功', data=result)


class ExcelAutoReadApi(MethodView):
    """Excel读操作相关Api"""

    def post(self):
        """
        Excel读操作
        :return:
        """

        data = request.get_json()
        excel_path = data.get('excel_path')
        sheet_name = data.get('sheet_name')
        action = data.get('action')
        read_range = data.get('read_range')
        read_expand = data.get('read_expand', {})
        kw = data.get('kw')
        data_only = read_expand.get('data_only', True)

        eh = ExcelReadHandle(excel_path=excel_path)
        eh.excel_open(read_only=True, data_only=data_only)
        if not eh.throw.get('status'):
            return api_result(code=10005, **eh.throw)

        result = eh.excel_read(sheet_name=sheet_name, read_range=read_range, **kw)
        return api_result(code=200, **result)


class ExcelAutoWriteApi(MethodView):
    """Excel写操作相关Api"""

    def post(self):
        """
        Excel写操作
        :return:
        """

        data = request.get_json()
        excel_path = data.get('excel_path')
        sheet_name = data.get('sheet_name')
        action = data.get('action')
        write_range = data.get('write_range')
        kw = data.get('kw')

        eh = ExcelWriteHandle(excel_path=excel_path)
        eh.excel_open()
        if not eh.throw.get('status'):
            return api_result(code=10005, **eh.throw)

        result = eh.excel_write(sheet_name=sheet_name, write_range=write_range, **kw)
        return api_result(code=200, **result)


class ExcelAutoDeleteApi(MethodView):
    """Excel删除操作相关Api"""

    def post(self):
        """
        Excel删除操作
        :return:
        """

        data = request.get_json()
        excel_path = data.get('excel_path')
        sheet_name = data.get('sheet_name')
        action = data.get('action')
        del_range = data.get('del_range')
        kw = data.get('kw')

        eh = ExcelDeleteHandle(excel_path=excel_path)
        eh.excel_open()
        if not eh.throw.get('status'):
            return api_result(code=10005, **eh.throw)

        result = eh.excel_del(sheet_name=sheet_name, del_range=del_range, **kw)
        return api_result(code=200, **result)


class ExcelAutoClearApi(MethodView):
    """Excel清除操作相关Api"""

    def post(self):
        """
        Excel清除操作
        :return:
        """

        data = request.get_json()
        excel_path = data.get('excel_path')
        sheet_name = data.get('sheet_name')
        action = data.get('action')
        clear_range = data.get('clear_range')
        kw = data.get('kw')

        eh = ExcelClearHandle(excel_path=excel_path)
        eh.excel_open()
        if not eh.throw.get('status'):
            return api_result(code=10005, **eh.throw)

        result = eh.excel_clear(sheet_name=sheet_name, clear_range=clear_range, **kw)
        return api_result(code=200, **result)


class ExcelAutoInsertApi(MethodView):
    """Excel插入操作相关Api"""

    def post(self):
        """
        Excel插入操作
        :return:
        """

        data = request.get_json()
        excel_path = data.get('excel_path')
        sheet_name = data.get('sheet_name')
        action = data.get('action')
        insert_range = data.get('insert_range')
        kw = data.get('kw')

        eh = ExcelInsertHandle(excel_path=excel_path)
        eh.excel_open()
        if not eh.throw.get('status'):
            return api_result(code=10005, **eh.throw)

        result = eh.excel_insert(sheet_name=sheet_name, insert_range=insert_range, **kw)
        return api_result(code=200, **result)


class ExcelAutoSortApi(MethodView):
    """Excel排序操作相关Api"""

    def post(self):
        """
        Excel插入操作
        :return:
        """

        data = request.get_json()
        excel_path = data.get('excel_path')
        sheet_name = data.get('sheet_name')
        action = data.get('action')
        sort_range = data.get('sort_range')
        kw = data.get('kw')

        eh = ExcelSortHandle(excel_path=excel_path)
        eh.excel_open()
        if not eh.throw.get('status'):
            return api_result(code=10005, **eh.throw)

        result = eh.excel_sort(sheet_name=sheet_name, sort_range=sort_range, **kw)
        return api_result(code=200, **result)


class ExcelAutoExtendApi(MethodView):
    """Excel扩展操作相关Api"""

    def post(self):
        """
        Excel扩展操作
        :return:
        """

        data = request.get_json()
        excel_path = data.get('excel_path')


api.add_url_rule('/dev_process', view_func=DevProcess.as_view('dev_process_api'))
# api.add_url_rule('/wx_send_message', view_func=WeChatSendMessageApi.as_view('wx_send_message_api'))
# api.add_url_rule('/wx_edit_pyq_auth', view_func=WeChatPyqAuthApi.as_view('wx_edit_pyq_auth_api'))
api.add_url_rule('/excel_auto_sheet', view_func=ExcelAutoSheetApi.as_view('excel_auto_sheet_api'))
api.add_url_rule('/excel_auto_read', view_func=ExcelAutoReadApi.as_view('excel_auto_read_api'))
api.add_url_rule('/excel_auto_write', view_func=ExcelAutoWriteApi.as_view('excel_auto_write_api'))
api.add_url_rule('/excel_auto_del', view_func=ExcelAutoDeleteApi.as_view('excel_auto_del_api'))
api.add_url_rule('/excel_auto_clear', view_func=ExcelAutoClearApi.as_view('excel_auto_clear_api'))
api.add_url_rule('/excel_auto_insert', view_func=ExcelAutoInsertApi.as_view('excel_auto_insert_api'))
api.add_url_rule('/excel_auto_sort', view_func=ExcelAutoSortApi.as_view('excel_auto_sort_api'))
api.add_url_rule('/excel_auto_extend', view_func=ExcelAutoExtendApi.as_view('excel_auto_extend_api'))

app = Flask(__name__)
app.register_blueprint(api, url_prefix='/api')

CORS(app, supports_credentials=True)

if __name__ == '__main__':
    """
    python -m pip install --upgrade pip -i https://pypi.doubanio.com/simple
    pip install flask flask-cors openpyxl shortuuid psutil pywinauto pandas -i https://pypi.doubanio.com/simple
    pip install pyinstaller==5.6.2 tinyaes pycryptodome -i https://pypi.doubanio.com/simple
    
    暂时不需要 pip install Lackey -i https://pypi.doubanio.com/simple
    
    3.8.10以下 -> win7, win8:
        pip freeze > reqirements-3.8.x.txt
        pip install -r reqirements-3.8.x.txt -i https://pypi.doubanio.com/simple
    
    3.9.4以上 -> win10, win11:
        pip freeze > reqirements.txt
        pip install -r reqirements.txt -i https://pypi.doubanio.com/simple
    
    
    pyinstaller -F -w --key yangyuexiong server.py
    pyinstaller -F -w --key yangyuexiong test_build.py
    
    """
    app.run(host='0.0.0.0', port=5000, debug=True)
